package bungaeting.net.client.android.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtil {
	private static Map<String, Object> toMap(JSONObject jsonObject, Map<String, Object> map){
		@SuppressWarnings("unchecked")
		Iterator<String> iterKeys = (Iterator<String>)jsonObject.keys();
		try {
			while (iterKeys.hasNext()) {
				String key = iterKeys.next();
				Object obj = jsonObject.get(key);;
				map.put(key, jsonObjectToObject(obj));
			}
		} catch (JSONException e) {
			System.err.println(e.toString());
			e.printStackTrace();
		}
		return map;
	}
	
	private static Object jsonObjectToObject(Object obj){
		
		if (obj instanceof Boolean){
			return (Boolean)obj;
		}
		else if (obj instanceof Double){
			return (Double)obj;
		}
		else if (obj instanceof Integer){
			return (Integer)obj;
		}
		else if (obj instanceof Long){
			return (Long)obj;
		}
		else if (obj instanceof String){
			return (String)obj;
		}
		else if (obj instanceof JSONArray){
			List<Object> list = new ArrayList<Object>();
			JSONArray jsonArray = (JSONArray)obj;
			
			int length = jsonArray.length();
			try {
				for (int i = 0 ; i < length ; i++){
					list.add(jsonObjectToObject(jsonArray.get(i)));
				}
			} catch (JSONException e) {
				System.err.println(e.toString());
				e.printStackTrace();
			}
			return list;
		}
		else if (obj instanceof JSONObject){
			Map<String, Object> mapSub = new HashMap<String, Object>();
			return toMap((JSONObject)obj, mapSub);
		}
		return null;
	}
	public static Map<String, Object> toMap(String json){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			toMap(new JSONObject(json), map);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.err.println(e.toString());
			e.printStackTrace();
		}
		return map;
	}
	
	public static Object toJSONObject(Object obj){
		
		if (obj instanceof Map){
			JSONObject jsonObject = new JSONObject();
			try {
				
				Map<String, Object> map = (Map<String, Object>)obj;
				for (String key : map.keySet()){
					Object val = map.get(key);
					jsonObject.putOpt(key, toJSONObject(val));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return jsonObject;
		}
		else if (obj instanceof List){
			return toJSONArray((List<Object>)obj);
		}
		else{
			return obj;
		}
		
	}
	public static JSONArray toJSONArray(List<Object> list){
		JSONArray jsonArray = new JSONArray();
		
		for (Object o : list){
			jsonArray.put(toJSONObject(o));
		}
		return jsonArray;
	}
	public static String toJSonString(Map<String, Object> map){
		
		return toJSONObject(map).toString();
	}
}
